<template>
  <div class="cursor-pointer inline-flex">
    <a-popover trigger="click" title="选择图片" v-model:open="visible">
      <slot>
        <SmileOutlined />
      </slot>
      <template #content>
        <a-card>
          <template #title>
            <a-radio-group
              option-type="button"
              @change="changeType"
              v-model:value="type"
              :options="imageOptions"
            ></a-radio-group>
          </template>
          <ul :class="[type, 'icon-list']" v-if="galleryData.length > 0">
            <li
              v-for="item in galleryData"
              @click="selectItem(item)"
              :class="[{ active: selectedSet.includes(item) }]"
              @dblclick="confirm"
              class="flex flex-s"
            >
              <a-tooltip :title="item">
                <img :src="getImageByFullPath(item)" />
              </a-tooltip>
            </li>
          </ul>
          <a-empty v-else />
          <template #actions>
            <div class="text-right pr-12 py-4 m-0">
              <a-button type="primary" @click="confirm" :disabled="selectedSet.length === 0">
                确定
              </a-button>
            </div>
          </template>
        </a-card>
      </template>
    </a-popover>
  </div>
</template>

<script setup lang="ts">
import { getImageByFullPath } from '@/api/utils/image';
import { getDictOption } from '@/global/data/dict';
import { DICT_ENUM } from '@/global/enum/common';
import type { IconType } from '@/types/system';
import localforage from 'localforage';

const imageOptions = ref();
const visible = ref(false);

const type = ref();
const props = withDefaults(
  defineProps<{
    limit?: number;
    modelValue: string;
    type?: IconType;
  }>(),
  {
    limit: 1,
    modelValue: '',
    type: 'image-icon',
  },
);

const emit = defineEmits(['update:modelValue']);

/* 已经选择的图片 */
const selectedSet = ref<string[]>([]);

const galleryData = ref<string[]>([]);

/* 选择图片 */
const selectItem = (item: string) => {
  if (props.limit <= selectedSet.value.length) {
    selectedSet.value.shift();
  }
  selectedSet.value.push(item);
};
const getTypes = async () => {
  imageOptions.value = await getDictOption(DICT_ENUM.SYS_GALLERY);
};
/**
 * @description:
 * 点击确定后关闭弹窗
 */
const confirm = () => {
  /* 如果是单选返回对象，否则返回数组 */
  if (props.limit === 1) {
    emit('update:modelValue', selectedSet.value[0]);
  } else {
    emit('update:modelValue', selectedSet.value);
  }
  visible.value = false;
};

const getImageData = async () => {
  const data = await localforage.getItem('images');
  try {
    imageOptions.value.map(async (e: any) => {
      if (type.value === e.value) {
        const jsonData = JSON.parse(JSON.stringify(data));
        galleryData.value = jsonData[e.value] || [];
      }
      return e;
    });
  } catch (error) {}
};
const changeType = () => {
  galleryData.value = [];
  getImageData();
};

watch(
  props,
  async () => {
    if (!imageOptions.value) {
      await getTypes();
    }
    type.value = props.type;
    getImageData();
  },
  {
    deep: true,
    immediate: true,
  },
);
</script>

<style lang="scss" scoped>
@import './style';
</style>
